package demo.utils;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class SerializeUtil {


    /**
     * object转为bytes，用于统计大小
     *
     * @param obj 对象
     * @return
     */
    public static int objectSize(Object obj) {
        if (obj == null || !isSerializable(obj)) {
            return 0;
        }
        byte[] bytes = new byte[0];
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes.length;
    }

    /**
     * 主要用于jedis的参数和结果的类型判断
     *
     * @param object 任何对象
     */
    private static boolean isSerializable(Object object) {
        if (object == null || !(object instanceof Serializable)) {
            return false;
        }

        if (object instanceof String || object instanceof byte[]) {
            return true;
        }

        if (object instanceof List) {
            List list = (List) object;
            if (list.size() > 0) {
                Object list0 = list.get(0);
                if (list0 instanceof Serializable) {
                    return true;
                }
            }
        }

        if (object instanceof Set) {
            Set set = (Set) object;
            Iterator iterator = set.iterator();
            if (iterator.hasNext()) {
                Object set0 = iterator.next();
                if (set0 instanceof Serializable) {
                    return true;
                }
            }
        }

        return false;
    }
}
